package top.zspaces.order.service.impl;

import com.alibaba.csp.sentinel.SphU;
import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import top.zspaces.order.bean.Order;
import top.zspaces.order.feign.ProductFeignClient;
import top.zspaces.order.service.OrderService;
import top.zspaces.product.bean.Product;

import java.math.BigDecimal;
import java.util.Arrays;
import java.util.List;

@Slf4j
@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    DiscoveryClient discoveryClient;
    @Autowired
    RestTemplate restTemplate;
    @Autowired
    LoadBalancerClient loadBalancerClient;
    @Autowired
    ProductFeignClient productFeignClient;

    @SentinelResource(value = "createOrder", blockHandler = "createOrderFallback")
    @Override
    public Order createOrder(Long productId, Long userId) {
        // Product product = getProductFromRemoteWithLoadBalanceAnnotation(productId);

        // 使用Feign远程调用
        Product product = productFeignClient.getProductById(productId);
        Order order = new Order();
        order.setId(1L);
        // 总金额计算
        order.setTotalAmount(product.getPrice().multiply(new BigDecimal(product.getNum())));
        order.setUserId(userId);
        order.setNickName("ZSpaces");
        order.setAddress("河南区域");
        //todo 远程调用查询商品列表未实现
        order.setProductList(Arrays.asList(product));

//        try {
//            SphU.entry("硬编码-流量控制");
//        } catch (BlockException e) {
//        编码处理
//            throw new RuntimeException(e);
//        }

        return order;
    }

    // 兜底回调
    public Order createOrderFallback(Long productId, Long userId, BlockException e) {
        Order order = new Order();
        order.setId(0L);
        order.setTotalAmount(new BigDecimal("0"));
        order.setUserId(userId);
        order.setNickName("未知用户-createOrderFallback-兜底回调");
        order.setAddress("未知信息：" + e.getClass());
        return order;
    }

    private Product getProductFromRemoteWithLoadBalanceAnnotation(Long productId) {
        // 3,使用@LoadBalanced注解进行负载均衡
        String uri = String.format("http://%s/product/%s", "service-product", productId);
        log.info("使用注解的负载均衡，远程请求uri: {}", uri);
        // 给远程发送请求：service-product会被动态替换。
        return restTemplate.getForObject(uri, Product.class);
    }

    private Product getProductFromRemoteWithLoadBalance(Long productId) {
        // 2,使用LoadBalancerClient进行负载均衡
        ServiceInstance choose = loadBalancerClient.choose("service-product");
        String host = choose.getHost();
        int port = choose.getPort();
        String uri = String.format("http://%s:%d/product/%s", host, port, productId);
        log.info("使用负载均衡，远程请求uri: {}", uri);
        //2,给远程发送请求
        return restTemplate.getForObject(uri, Product.class);
    }

    private Product getProductFromRemote(Long productId) {
        // 1,获取到远程调用所需的信息，商品服务所在的所有机器IP+Port。
        List<ServiceInstance> instances = discoveryClient.getInstances("service-product");
        ServiceInstance instance = instances.getFirst();
        String host = instance.getHost();
        int port = instance.getPort();
        // 远程URL地址
        String uri = String.format("http://%s:%d/product/%s", host, port, productId);
        log.info("远程请求uri: {}", uri);
        //2,给远程发送请求
        return restTemplate.getForObject(uri, Product.class);
    }
}
